package com.wpx.log.core.handler;

import java.lang.reflect.Field;

import javax.servlet.http.HttpServletRequest;

import org.springframework.util.StringUtils;

import com.wpx.log.core.LogContext;
import com.wpx.log.core.LogRequestContext;

import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;

public class OpUserAgentLogHandler implements ILogHandler {

	@Override
	public boolean isSync() {
		return true;
	}
	
	@Override
	public Object handler(LogContext logContext, LogRequestContext logRequestContext, Field logField) {
		HttpServletRequest request = logRequestContext.getHttpServletRequest();
	
		String agent = request.getHeader("User-Agent");
		
		if(StringUtils.isEmpty(agent)) {
			return "";
		}
		
		//解析agent字符串
		UserAgent userAgent = UserAgent.parseUserAgentString(agent);
		//获取浏览器对象
		Browser browser = userAgent.getBrowser();
		//获取操作系统对象
		OperatingSystem operatingSystem = userAgent.getOperatingSystem();
		
//		System.out.println("userAgent:" + agent);
//		System.out.println("浏览器名:"+browser.getName());
//		System.out.println("浏览器类型:"+browser.getBrowserType());
//		System.out.println("浏览器家族:"+browser.getGroup());
//		System.out.println("浏览器生产厂商:"+browser.getManufacturer());
//		System.out.println("浏览器使用的渲染引擎:"+browser.getRenderingEngine());
//		System.out.println("浏览器版本:"+userAgent.getBrowserVersion());
//		        
//		System.out.println("操作系统名:"+operatingSystem.getName());
//		System.out.println("访问设备类型:"+operatingSystem.getDeviceType());
//		System.out.println("操作系统家族:"+operatingSystem.getGroup());
//		System.out.println("操作系统生产厂商:"+operatingSystem.getManufacturer());
//		
		if("UNKNOWN".equalsIgnoreCase(browser.getName())) {
			return agent;
		}
		
		StringBuilder sb = new StringBuilder();
		sb.append(browser.getName()).append(userAgent.getBrowserVersion()).append("/").append(browser.getRenderingEngine()).append("/").append(operatingSystem.getName());
		return sb.toString();
	}

}
